package com.pfzy.utildemo.utils;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;

import androidx.core.app.NotificationCompat;

import com.pfzy.utildemo.R;

public class NotificationUtils {
    public static final int NOTIFY_ID = 2001;

    public static Notification buildNotification(Context context) {
        try {
            Context mContext = context.getApplicationContext();
            NotificationChannel channel = NotificationChannelUtil.getDefaultNotificationChannelId(mContext);

            NotificationCompat.Builder builder = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                channel.enableLights(true);// 是否在桌面icon右上角展示小圆点
                channel.setLightColor(Color.BLUE); // 小圆点颜色
                channel.setShowBadge(true); // 是否在久按桌面图标时显示此渠道的通知
                builder = new NotificationCompat.Builder(mContext, channel.getId());
            } else {
                builder = new NotificationCompat.Builder(mContext, NotificationChannelUtil.DEFAULT_CHANNEL_ID);
            }
            builder.setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(getAppName(mContext))
                    .setContentText("正在后台运行")
                    .setWhen(System.currentTimeMillis());
            return builder.build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取app的名称
     */
    public static String getAppName(Context context) {
        String appName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            appName = context.getResources().getString(labelRes);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return appName;
    }
}
